<template>
  <div class="page-container">
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>筛选订单</span>
        </div>
      </template>
      <el-form :inline="true" :model="queryPage" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="queryPage.order_number" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryPage.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待分配" :value="0" />
            <el-option label="已分配" :value="1" />
            <el-option label="配送中" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
            <el-option label="已支付" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon>搜索</el-button>
          <el-button @click="resetSearch"><el-icon><Refresh /></el-icon>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="actions-header">
      <h3 class="orders-title">我的订单 ({{ queryPage.total }})</h3>
      <el-button type="primary" size="large" @click="showCreateOrderDialog" class="create-order-btn">
        <el-icon><Plus /></el-icon>新建订单
      </el-button>
    </div>

    <div class="order-list" v-loading="loading">
      <el-card v-for="order in orders" :key="order.id" class="order-card">
        <template #header>
          <div class="order-card-header">
            <span class="order-number">订单号: {{ order.orderNumber }}</span>
            <el-tag :type="getStatusType(order.status)" effect="dark" size="small">{{ getStatusText(order.status) }}</el-tag>
          </div>
        </template>
        <div class="order-card-body">
          <div class="order-info-item">
            <el-icon><LocationInformation /></el-icon>
            <span><strong>配送地址:</strong> {{ order.mudidi3 }}</span>
          </div>
          <div class="order-info-item">
            <el-icon><Box /></el-icon>
            <span><strong>送货目的地:</strong> {{ order.zhongdian }}</span>
          </div>
          <div class="order-info-item">
            <el-icon><Clock /></el-icon>
            <span><strong>配送时间:</strong> {{ order.deliveryTime }}</span>
          </div>
          <div class="order-info-item" v-if="order.deliveryname">
            <el-icon><User /></el-icon>
            <span><strong>配送员:</strong> {{ order.deliveryname }}</span>
          </div>
        </div>
        <div class="order-card-footer" >
          <el-button type="primary" link @click="viewOrderDetail(order)">
            <el-icon><View /></el-icon>查看详情
          </el-button>
          <el-button v-if="order.status === 0" type="danger" link @click="cancelOrder(order)">
            <el-icon><Close /></el-icon>取消订单
          </el-button>
            <el-button v-if="order.status===3" @click="pay(order)" type="success" text>
              <el-icon><Coin /></el-icon>支付运费
            </el-button>

          <el-button @click="selDitu(order)" type="success" text>
            <el-icon><Coin /></el-icon>查看地图
          </el-button>

        </div>
      </el-card>
      <el-empty v-if="!orders.length && !loading" description="暂无订单"></el-empty>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryPage.current"
        v-model:page-size="queryPage.size"
        :page-sizes="[3, 6, 8, 10]"
        :total="queryPage.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新建订单对话框 -->
    <el-dialog
      v-model="createOrderDialogVisible"
      title="新建订单"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="createOrderFormRef"
        :model="createOrderForm"
        :rules="createOrderRules"
        label-width="100px"
      >
        <el-form-item label="配送地址" prop="addressId">
          <el-select v-model="createOrderForm.addressId" placeholder="请选择配送地址">
            <el-option
                v-for="address in addresses"
                :key="address.id"
                :label="address.isDefault === 1 ? `${address.address}（默认）` : address.address"
                :value="address.id"
            />
          </el-select>
        </el-form-item>
        <div v-if="defaultAddressText" style="font-size: 12px; color: #909399; margin-left: 100px; margin-top: -15px; margin-bottom: 22px;">
          默认地址: {{ defaultAddressText }}
        </div><br/>
        <el-form-item label="配送时间" prop="deliveryTime">
          <el-date-picker
            v-model="createOrderForm.deliveryTime"
            type="datetime"
            placeholder="请选择配送时间"
            style="width: 100%"
          />
<!--          <el-input v-model="createOrderForm.deliveryTime"/>-->
        </el-form-item><br/>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="createOrderForm.notes" type="text" :rows="3" placeholder="请输入订单备注"/>
        </el-form-item><br/>
        <el-form-item label="货物目的地" prop="zhongdian">
          <el-input v-model="createOrderForm.zhongdian" type="text" :rows="3" placeholder="请输入货物目的地"/>
        </el-form-item><br/>
        <el-form-item label="定义金额" prop="jiage">
          <el-input v-model="createOrderForm.jiage" type="text" :rows="3" placeholder="请输入运送金额"/>
        </el-form-item>
        <el-text style="font-size: 9px">金额定义建议 : 重量<10kg 100元以内 | 100kg>重量>10kg 3000以内 | 重量>100kg 多余按每kg+20元算</el-text>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createOrder" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailDialogVisible"
      title="订单详情"
      width="700px"
      :close-on-click-modal="false"
      class="order-detail-dialog"
    >
      <el-steps :active="currentOrderDetail.status" finish-status="success" align-center class="order-timeline">
        <el-step title="待分配"></el-step>
        <el-step title="已分配"></el-step>
        <el-step title="配送中"></el-step>
        <el-step title="已完成"></el-step>
      </el-steps>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrderDetail.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentOrderDetail.status)">
            {{ getStatusText(currentOrderDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ currentOrderDetail.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="配送时间">{{ currentOrderDetail.deliveryTime }}</el-descriptions-item>
        <el-descriptions-item label="配送地址">{{ currentOrderDetail.mudidi3 }}</el-descriptions-item>
        <el-descriptions-item label="目的地">{{ currentOrderDetail.zhongdian }}</el-descriptions-item>
        <el-descriptions-item label="配送费用">{{ currentOrderDetail.jiage }}</el-descriptions-item>
        <el-descriptions-item label="配送员">{{ currentOrderDetail.deliveryname || '未分配' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrderDetail.notes || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="orderDetailDialogVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, View, Close, Coin, LocationInformation, Clock, Box, User } from '@element-plus/icons-vue'
import axios from "axios";
import {useUserStore} from "@/pinia/index.js";
import router from "@/router/index.js";

// 搜索表单
const searchForm = reactive({
  orderNumber: '',
  status: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
var useUserStore1 = useUserStore();
// 订单数据
const orders = ref([
  {
    id:"",
    orderNumber: '',
    status: '',
    deliveryTime: '',
    mudidi3: '',
    deliveryname: '',
    createdAt: '',
    notes: '',
    zhongdian:"",
    jiage:""
  },
])
const aaa=ref(Array.from({ length: 3 }, () =>
    String.fromCharCode(65 + Math.floor(Math.random() * 26))).join(''))
const bbb=ref(Array.from({ length: 6 }, () =>
    Math.floor(Math.random() * 10)).join(''))
//获取所有订单数据
const queryPage=ref({
  current:1,
  size: 3,
  order_number:null,
  status:null,
  userId:useUserStore1.getUserId,
  total:null
})
const getOrderAll=()=>{
  axios({
    url:"/UserApi/user/findAllPage",
    method:"post",
    data:queryPage.value
  }).then(res=>{
    orders.value=res.data.data.records
    queryPage.value.total=res.data.data.total
    console.log(res.data.data.total)
  })
}
getOrderAll()

//地图调用地点
const selDitu=(order)=>{
  useUserStore1.setStartName(order.mudidi3);
  useUserStore1.setEndName(order.zhongdian);
  // location.href='src/views/user/ditu.vue'
  router.push("ditu")
}

// 新建订单相关
const createOrderDialogVisible = ref(false)
const createOrderFormRef = ref(null)
const createOrderForm = reactive({
  orderNumber:aaa.value+bbb.value,
  userId:useUserStore1.getUserId,
  addressId: null,
  deliveryTime: '',
  notes: '',
  zhongdian:'',
  jiage:''
})

const submitting = ref(false)

// 模拟地址数据
const addresses = ref([
  { id: null, address: '' ,isDefault:null},
])

const defaultAddressText = computed(() => {
  const defaultAddr = addresses.value.find(a => a.isDefault === 1);
  return defaultAddr ? defaultAddr.address : null;
});

const getAddressAll=(userId)=>{
  axios({
    url:"/UserApi/user/addressSel",
    method:"post",
    params:{userId:userId}
  }).then(res=>{
    addresses.value=res.data
    console.log(res.data)

    const defaultAddress = addresses.value.find(addr => addr.isDefault === 1);
    if (defaultAddress) {
      createOrderForm.addressId = defaultAddress.id; // 关键：绑定默认地址ID
    }
  })
}
getAddressAll(useUserStore().getUserId)
const createOrderRules = {
  addressId: [
    { required: true, message: '请选择配送地址', trigger: 'change' }
  ],
  deliveryTime: [
    { required: true, message: '请选择配送时间', trigger: 'change' }
  ],
  notes: [
    { required: true, message: '请添加备注', trigger: 'change' }
  ],
  zhongdian: [
    { required: true, message: '请添加目的地', trigger: 'change' }
  ],
  jiage: [
    { required: true, message: '请添加价格', trigger: 'change' }
  ]
}

// 订单详情对话框相关
const orderDetailDialogVisible = ref(false)
const currentOrderDetail = reactive({
  orderNumber: '',
  status: 0,
  createdAt: '',
  deliveryTime: '',
  address: '',
  deliveryman: '',
  notes: '',
  zhongdian:"",
  jiage:""
})
// 状态相关方法
const getStatusType = (status) => {
  const types = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'success',
    4: 'danger',
    5: 'primary'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    0: '待分配',
    1: '已分配',
    2: '配送中',
    3: '已完成',
    4: '已取消',
    5: '已支付'
  }
  return texts[status] || '未知状态'
}

// 搜索相关方法
const handleSearch = () => {
  getOrderAll();
}

const resetSearch = () => {
  queryPage.value.order_number = null;
  queryPage.value.status = null;
  getOrderAll();
  // handleSearch()
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryPage.value.size=val
  queryPage.value.current = 1
  getOrderAll()
  // handleSearch()
}

const handleCurrentChange = (val) => {
  queryPage.value.current=val
  getOrderAll()
  // handleSearch()
}
const pay=(order)=>{
  window.open('http://localhost:5000/alipay/pay?id='+order.id)
}
// 订单相关方法
const showCreateOrderDialog = () => {
  createOrderFormRef.value?.resetFields()
  // 查找默认地址并设置为表单的初始值
  const defaultAddress = addresses.value.find(addr => addr.isDefault === 1);
  if (defaultAddress) {
    createOrderForm.addressId = defaultAddress.id;
  }
  createOrderDialogVisible.value = true
}

const createOrder = () => {
  axios({
    url:"/UserApi/user/orderAdd",
    method:"post",
    data:createOrderForm
  }).then(res=>{
    submitting.value = true
    setTimeout(() => {
      ElMessage.success('订单创建成功')
      createOrderDialogVisible.value = false
      submitting.value = false
      getOrderAll()
    }, 1000)
  })
}


const viewOrderDetail = (order) => {
  currentOrderDetail.orderNumber = order.orderNumber
  currentOrderDetail.status = order.status
  currentOrderDetail.createdAt = order.createdAt
  currentOrderDetail.deliveryTime = order.deliveryTime
  currentOrderDetail.mudidi3 = order.mudidi3
  currentOrderDetail.deliveryname = order.deliveryname
  currentOrderDetail.notes = order.notes
  currentOrderDetail.zhongdian = order.zhongdian
  currentOrderDetail.jiage = order.jiage
  orderDetailDialogVisible.value = true
}

const cancelOrder = (row) => {
  ElMessageBox.confirm(
      `确定要取消订单 ${row.orderNumber} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 发送取消请求
    axios({
      url: "/UserApi/user/quXiao",
      method: "post",
      params: { id: row.id }
    }).then(res => {
      // if (res.data.code === 200) {
        ElMessage.success(`订单 ${row.orderNumber} 已取消`);
        getOrderAll(useUserStore().getUserId)// 替换为你的数据加载函数名
        // location.reload()
      // }
    }).catch(error => {
      ElMessage.error("取消订单失败: " + error.message);
    });
  }).catch(() => {
    // 用户点击取消，什么都不做
  });

}
</script>

<style scoped>
.page-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.search-card,
.table-card {
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  background: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.search-form {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.actions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.orders-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.create-order-btn {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.order-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
}

.order-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}

.order-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-number {
  font-weight: 600;
  color: #303133;
}

.order-card-body {
  padding: 16px 0;
  font-size: 14px;
  color: #606266;
}

.order-info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.order-info-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.order-card-footer {
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.order-timeline {
  margin-bottom: 24px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa !important;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 16px 24px;
  background-color: #f7f8fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
}

.el-button .el-icon {
  margin-right: 4px;
}
</style> 